{% extends theme_path('admin/base.html') %}

{% block title %}评论管理{% endblock %}

{% block content %}
<div class="p-6">
    <div class="bg-white rounded-lg shadow-sm">
        <!-- Tab 切换 -->
        <div class="border-b border-gray-200">
            <nav class="flex -mb-px">
                <button onclick="switchTab('comments')"
                        class="tab-button flex-1 sm:flex-none px-6 py-4 border-b-2 font-medium text-sm transition-all duration-200
                               {% if active_tab == 'comments' %}
                               border-blue-500 text-blue-600 bg-blue-50
                               {% else %}
                               border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 hover:bg-gray-50
                               {% endif %}">
                    <div class="flex items-center space-x-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"></path>
                        </svg>
                        <span>评论列表</span>
                    </div>
                </button>
                <button onclick="switchTab('config')"
                        class="tab-button flex-1 sm:flex-none px-6 py-4 border-b-2 font-medium text-sm transition-all duration-200
                               {% if active_tab == 'config' %}
                               border-blue-500 text-blue-600 bg-blue-50
                               {% else %}
                               border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 hover:bg-gray-50
                               {% endif %}">
                    <div class="flex items-center space-x-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                        </svg>
                        <span>评论设置</span>
                    </div>
                </button>
            </nav>
        </div>

        <!-- 评论列表内容 -->
        <div id="comments-tab" class="{% if active_tab != 'comments' %}hidden{% endif %}">
            <div class="px-6 py-4 border-b">
                <div class="flex flex-col lg:flex-row justify-between items-stretch lg:items-center space-y-4 lg:space-y-0">
                    <h2 class="text-xl font-bold">评论管理</h2>
                    <div class="flex flex-col sm:flex-row items-stretch sm:items-center space-y-4 sm:space-y-0 sm:space-x-4 w-full lg:w-auto">
                        <!-- 批量操作按钮 -->
                        <div class="flex items-center space-x-2">
                            <button onclick="toggleAllComments()" 
                                    class="px-3 py-1 text-sm border border-gray-200 rounded hover:bg-gray-50">
                                全选
                            </button>
                            <button onclick="batchDeleteComments()" 
                                    class="px-3 py-1 text-sm bg-red-100 text-red-700 rounded hover:bg-red-200"
                                    id="batchDeleteBtn" disabled>
                                批量删除
                            </button>
                        </div>
                        <form method="get" class="flex flex-col sm:flex-row items-stretch sm:items-center space-y-4 sm:space-y-0 sm:space-x-4 flex-1">
                            <div class="relative">
                                <select name="search_type" 
                                       class="px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full sm:w-auto"
                                       onchange="toggleStatusHelp(this.value)">
                                    <option value="content" {% if search_type == 'content' %}selected{% endif %}>内容</option>
                                    <option value="id" {% if search_type == 'id' %}selected{% endif %}>ID</option>
                                    <option value="author" {% if search_type == 'author' %}selected{% endif %}>评论者</option>
                                    <option value="article" {% if search_type == 'article' %}selected{% endif %}>文章</option>
                                    <option value="status" {% if search_type == 'status' %}selected{% endif %}>状态</option>
                                </select>

                                <!-- 改进的状态搜索提示框 -->
                                <div id="statusHelp" class="hidden absolute z-10 mt-2 w-64 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700">
                                    <div class="p-4">
                                        <h4 class="text-sm font-medium text-gray-900 dark:text-white mb-3">可用的状态值：</h4>
                                        <div class="space-y-2">
                                            <div class="flex items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 p-2 rounded-md" onclick="setStatusSearch('approved')">
                                                <span class="w-2 h-2 bg-green-500 rounded-full mr-2"></span>
                                                <span class="text-sm text-gray-600 dark:text-gray-300">approved - 已通过</span>
                                            </div>
                                            <div class="flex items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 p-2 rounded-md" onclick="setStatusSearch('pending')">
                                                <span class="w-2 h-2 bg-yellow-500 rounded-full mr-2"></span>
                                                <span class="text-sm text-gray-600 dark:text-gray-300">pending - 待审核</span>
                                            </div>
                                            <div class="flex items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 p-2 rounded-md" onclick="setStatusSearch('rejected')">
                                                <span class="w-2 h-2 bg-red-500 rounded-full mr-2"></span>
                                                <span class="text-sm text-gray-600 dark:text-gray-300">rejected - 已拒绝</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="relative flex-1">
                                <input type="text" name="q" id="searchInput" value="{{ search_query }}"
                                       placeholder="搜索评论..." 
                                       class="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                </div>
                            </div>
                            <button type="submit" class="w-full sm:w-auto px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                                搜索
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- 评论列表 -->
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="w-12 px-4 py-3">
                                <input type="checkbox" id="selectAll" class="rounded border-gray-300">
                            </th>
                            <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                            <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">评论信息</th>
                            <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">评论文章</th>
                            <th class="hidden sm:table-cell px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">评论状态</th>
                            <th class="px-4 sm:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        {% for comment in pagination.items %}
                        <tr class="hover:bg-gray-50">
                            <td class="px-4 py-4">
                                <input type="checkbox" name="comment_ids" value="{{ comment.id }}"
                                       class="comment-checkbox rounded border-gray-300"
                                       onchange="updateBatchDeleteButton()">
                            </td>
                            <td class="px-4 sm:px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ comment.id }}</td>

                            <td class="px-6 py-4 space-y-3">
                                <!-- 评论者信息 -->
                                <div class="flex items-center justify-between">
                                    <div class="flex items-center space-x-3">
                                        {% if comment.user %}
                                            <img src="{{ comment.user.avatar }}" alt="avatar" 
                                                 class="w-10 h-10 rounded-full object-cover">
                                            <div>
                                                <a href="{{ url_for('user.author', id=comment.user.id) }}" 
                                                   class="text-sm font-medium text-gray-900 hover:text-blue-600">
                                                   {{ comment.user.nickname or comment.user.username }}
                                                </a>
                                            </div>
                                        {% else %}
                                            <div class="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
                                                <svg class="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                                </svg>
                                            </div>
                                            <div>
                                                <div class="text-sm font-medium text-gray-900">
                                                    {{ comment.guest_name or '游客' }}
                                                </div>
                                                {% if comment.guest_email %}
                                                    <div class="text-xs text-gray-500">{{ comment.guest_email }}</div>
                                                {% endif %}
                                                {% if comment.guest_contact %}
                                                    <div class="text-xs text-gray-500">{{ comment.guest_contact }}</div>
                                                {% endif %}
                                            </div>
                                        {% endif %}
                                    </div>
                                    <!-- 时间显示 -->
                                    <div class="text-xs text-gray-500 whitespace-nowrap">
                                        {{ comment.created_at.strftime('%Y-%m-%d %H:%M') }}
                                    </div>
                                </div>

                                <!-- 评论内容 -->
                                <div class="text-sm text-gray-900">
                                    <div class="line-clamp-2">{{ comment.content }}</div>
                                </div>

                                <!-- 回复信息 -->
                                {% if comment.parent_id or comment.reply_to_id %}
                                    <div class="text-xs text-gray-500 bg-gray-50 p-2 rounded">
                                        <div class="font-medium">
                                            {% if comment.reply_to_id %}
                                                回复给 {{ comment.reply_to.guest_name or comment.reply_to.user.nickname or comment.reply_to.user.username }}:
                                            {% else %}
                                                回复给 {{ comment.parent.guest_name or comment.parent.user.nickname or comment.parent.user.username }}:
                                            {% endif %}
                                        </div>
                                        <div class="mt-1">
                                            {% if comment.reply_to_id %}
                                                {{ comment.reply_to.content|truncate(50) }}
                                            {% else %}
                                                {{ comment.parent.content|truncate(50) }}
                                            {% endif %}
                                        </div>
                                    </div>
                                {% endif %}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                {% if comment.article %}
                                    <a href="{{ ArticleUrlGenerator.generate(comment.article.id, comment.article.category_id, comment.article.created_at) }}"
                                       class="text-blue-600 hover:text-blue-900">
                                        {{ comment.article.title }}
                                    </a>
                                {% elif comment.custom_page %}
                                    <a href="{{ comment.custom_page.route }}"
                                       class="text-blue-600 hover:text-blue-900">
                                        {{ comment.custom_page.title }}
                                    </a>
                                {% else %}
                                    <span class="text-gray-500">已删除</span>
                                {% endif %}
                            </td>
                            <td class="hidden sm:table-cell px-6 py-4 whitespace-nowrap">
                                <div class="relative" x-data="{ open: false }">
                                    <button @click="open = !open"
                                            class="px-2 py-1 text-xs font-semibold rounded-full
                                                   {% if comment.status == 'approved' %}
                                                   bg-green-100 text-green-800 hover:bg-green-200
                                                   {% elif comment.status == 'pending' %}
                                                   bg-yellow-100 text-yellow-800 hover:bg-yellow-200
                                                   {% else %}
                                                   bg-red-100 text-red-800 hover:bg-red-200
                                                   {% endif %}">
                                        {{ {'approved': '已通过', 'pending': '待审核', 'rejected': '已拒绝'}[comment.status] }}
                                        <svg class="inline-block w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                                        </svg>
                                    </button>
                                    
                                    <!-- 下拉菜单 -->
                                    <div x-show="open"
                                         @click.away="open = false"
                                         class="absolute z-10 mt-1 w-40 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5">
                                        <div class="py-1">
                                            <button onclick="updateCommentStatus({{ comment.id }}, 'approved')"
                                                    class="block w-full px-4 py-2 text-sm text-left text-gray-700 hover:bg-gray-100">
                                                标记为已通过
                                            </button>
                                            <button onclick="updateCommentStatus({{ comment.id }}, 'pending')"
                                                    class="block w-full px-4 py-2 text-sm text-left text-gray-700 hover:bg-gray-100">
                                                标记为待审核
                                            </button>
                                            <button onclick="updateCommentStatus({{ comment.id }}, 'rejected')"
                                                    class="block w-full px-4 py-2 text-sm text-left text-gray-700 hover:bg-gray-100">
                                                标记为已拒绝
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-4 sm:px-6 py-4 whitespace-nowrap text-sm">
                                <div class="flex items-center space-x-4">
                                    <button onclick="deleteComment({{ comment.id }})"
                                            class="text-red-600 hover:text-red-900">
                                        删除
                                    </button>
                                    <a href="{{ ArticleUrlGenerator.generate(comment.article.id, comment.article.category_id, comment.article.created_at) }}#comment-{{ comment.id }}"
                                       target="_blank"
                                       class="text-blue-600 hover:text-blue-900">
                                        查看
                                    </a>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            {% if pagination.pages > 1 %}
            <div class="px-6 py-4 border-t">
                {% with endpoint='admin.comments', kwargs={'q': search_query, 'search_type': search_type} %}
                {% include 'components/pagination.html' %}
                {% endwith %}
            </div>
            {% endif %}
        </div>

        <!-- 评论设置内容 -->
        <div id="config-tab" class="{% if active_tab != 'config' %}hidden{% endif %} p-6">
            <form id="commentConfigForm" class="max-w-3xl mx-auto space-y-6">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                
                <!-- 每页显示评论数 -->
                <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <h3 class="text-lg font-medium text-gray-900 dark:text-white">每页显示评论数</h3>
                            <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">设置每页显示的评论数量</p>
                        </div>
                        <input type="number" id="commentsPerPage" name="comments_per_page" 
                               value="{{ comment_config.comments_per_page }}"
                               min="1" max="100"
                               class="w-24 px-3 py-2 border border-gray-200 dark:border-gray-600 rounded-lg focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white">
                    </div>
                </div>

                <!-- 评论审核设置 -->
                <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
                    <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">评论审核</h3>
                    <div class="space-y-4">
                        <label class="flex items-center p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200">
                            <input type="checkbox" id="requireAudit" name="require_audit"
                                   {% if comment_config.require_audit %}checked{% endif %}
                                   class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                            <div class="ml-3">
                                <div class="text-sm font-medium text-gray-900 dark:text-white">所有评论需要审核</div>
                                <p class="text-sm text-gray-500 dark:text-gray-400">开启后，所有评论将在审核通过后才会显示</p>
                            </div>
                        </label>
                    </div>
                </div>

                <!-- 游客评论设置 -->
                <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
                    <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">游客评论</h3>
                    <div class="space-y-4">
                        <label class="flex items-center p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200">
                            <input type="checkbox" id="allowGuest" name="allow_guest"
                                   {% if comment_config.allow_guest %}checked{% endif %}
                                   class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                            <div class="ml-3">
                                <div class="text-sm font-medium text-gray-900 dark:text-white">允许游客评论</div>
                                <p class="text-sm text-gray-500 dark:text-gray-400">开启后，未登录用户也可以发表评论</p>
                            </div>
                        </label>

                        <!-- 游客评论附加选项 -->
                        <div class="ml-8 space-y-4" id="guestOptions">
                            <label class="flex items-center p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200">
                                <input type="checkbox" id="requireEmail" name="require_email"
                                       {% if comment_config.require_email %}checked{% endif %}
                                       class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                                <div class="ml-3">
                                    <div class="text-sm font-medium text-gray-900 dark:text-white">必须填写邮箱</div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">游客评论时必须提供邮箱地址</p>
                                </div>
                            </label>

                            <label class="flex items-center p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-200">
                                <input type="checkbox" id="requireContact" name="require_contact"
                                       {% if comment_config.require_contact %}checked{% endif %}
                                       class="w-4 h-4 text-blue-600 rounded border-gray-300 focus:ring-blue-500">
                                <div class="ml-3">
                                    <div class="text-sm font-medium text-gray-900 dark:text-white">必须填写联系方式</div>
                                    <p class="text-sm text-gray-500 dark:text-gray-400">游客评论时必须提供联系方式</p>
                                </div>
                            </label>
                        </div>
                    </div>
                </div>

                <!-- 保存按钮 -->
                <div class="flex justify-end">
                    <button type="button" onclick="saveCommentConfig()"
                            class="px-6 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200 flex items-center">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                        </svg>
                        保存设置
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function switchTab(tab) {
    // 更新 URL 参数
    const url = new URL(window.location);
    url.searchParams.set('tab', tab);
    window.history.pushState({}, '', url);
    
    // 切换 tab 显示
    document.querySelectorAll('.tab-button').forEach(btn => {
        const isActive = btn.getAttribute('onclick').includes(tab);
        
        // 移除所有状态类
        btn.classList.remove(
            'border-blue-500', 'text-blue-600', 'bg-blue-50',
            'border-transparent', 'text-gray-500'
        );
        
        // 添加新的状态类
        if (isActive) {
            btn.classList.add('border-blue-500', 'text-blue-600', 'bg-blue-50');
        } else {
            btn.classList.add('border-transparent', 'text-gray-500', 'hover:text-gray-700', 'hover:border-gray-300', 'hover:bg-gray-50');
        }
    });
    
    // 切换内容显示
    document.getElementById('comments-tab').classList.toggle('hidden', tab !== 'comments');
    document.getElementById('config-tab').classList.toggle('hidden', tab !== 'config');
}

function saveCommentConfig() {
    const form = document.getElementById('commentConfigForm');
    const formData = new FormData();
    
    // 获取所有设置值
    formData.append('require_audit', document.getElementById('requireAudit').checked);
    formData.append('allow_guest', document.getElementById('allowGuest').checked);
    formData.append('require_email', document.getElementById('requireEmail').checked);
    formData.append('require_contact', document.getElementById('requireContact').checked);
    formData.append('comments_per_page', document.getElementById('commentsPerPage').value);
    formData.append('csrf_token', form.querySelector('[name="csrf_token"]').value);
    
    fetch('{{ admin_url }}/comments/config', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showAlert(data.error, 'error', '错误');
        } else {
            showAlert('评论设置已更新', 'success', '成功');
            setTimeout(() => location.reload(), 500);  // 添加页面刷新
        }
    });
}

function deleteComment(commentId) {
    showAlert('确定要删除此评论吗？此操作不可恢复！', 'warning', '确认删除', function() {
        fetch(`{{ admin_url }}/comments/${commentId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': '{{ csrf_token() }}'
            }
        }).then(response => {
            if (response.ok) {
                showAlert('评论删除成功', 'success', '成功');
                setTimeout(() => location.reload(), 200);
            } else {
                response.json().then(data => {
                    showAlert(data.error, 'error', '错误');
                });
            }
        });
    });
}

function approveComment(commentId) {
    fetch(`{{ admin_url }}/comments/${commentId}/approve`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    }).then(response => {
        if (response.ok) {
            showAlert('评论已通过', 'success', '成功');
            setTimeout(() => location.reload(), 200);
        } else {
            response.json().then(data => {
                showAlert(data.error, 'error', '错误');
            });
        }
    });
}

function rejectComment(commentId) {
    fetch(`{{ admin_url }}/comments/${commentId}/reject`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    }).then(response => {
        if (response.ok) {
            showAlert('评论已拒绝', 'success', '成功');
            setTimeout(() => location.reload(), 200);
        } else {
            response.json().then(data => {
                showAlert(data.error, 'error', '错误');
            });
        }
    });
}

function updateCommentStatus(commentId, status) {
    fetch(`{{ admin_url }}/comments/${commentId}/status`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token() }}'
        },
        body: JSON.stringify({ status: status })
    }).then(response => {
        if (response.ok) {
            // 找到对应的状态按钮和下拉菜单
            const statusBtn = document.querySelector(`button[onclick="updateCommentStatus(${commentId}, '${status}')"]`).closest('.relative');
            const mainBtn = statusBtn.querySelector('button:first-child');
            
            // 更新状态按钮的样式和文本
            const statusText = {
                'approved': '已通过',
                'pending': '待审核',
                'rejected': '已拒绝'
            }[status];
            
            const statusClasses = {
                'approved': 'bg-green-100 text-green-800 hover:bg-green-200',
                'pending': 'bg-yellow-100 text-yellow-800 hover:bg-yellow-200',
                'rejected': 'bg-red-100 text-red-800 hover:bg-red-200'
            }[status];
            
            // 移除所有可能的状态类
            mainBtn.classList.remove(
                'bg-green-100', 'text-green-800', 'hover:bg-green-200',
                'bg-yellow-100', 'text-yellow-800', 'hover:bg-yellow-200',
                'bg-red-100', 'text-red-800', 'hover:bg-red-200'
            );
            
            // 添加新的状态类
            mainBtn.classList.add(...statusClasses.split(' '));
            
            // 更新按钮文本
            mainBtn.innerHTML = `
                ${statusText}
                <svg class="inline-block w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                </svg>
            `;
            
            // 关闭下拉菜单
            statusBtn.__x.$data.open = false;
            
            showAlert('评论状态已更新', 'success', '成功');
        } else {
            response.json().then(data => {
                showAlert(data.error, 'error', '错误');
            });
        }
    });
}

function toggleStatusHelp(value) {
    const helpBox = document.getElementById('statusHelp');
    if (value === 'status') {
        helpBox.classList.remove('hidden');
        // 如果是状态搜索，自动聚焦搜索框
        document.getElementById('searchInput').focus();
    } else {
        helpBox.classList.add('hidden');
    }
}

// 添加点击状态值的处理函数
function setStatusSearch(status) {
    document.getElementById('searchInput').value = status;
    document.getElementById('statusHelp').classList.add('hidden');
}

// 点击其他地方关闭提示框
document.addEventListener('click', function(e) {
    const helpBox = document.getElementById('statusHelp');
    const select = document.querySelector('select[name="search_type"]');
    if (!helpBox.contains(e.target) && !select.contains(e.target)) {
        helpBox.classList.add('hidden');
    }
});

// 初始化时根据 URL 参数切换 tab
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const tab = urlParams.get('tab') || 'comments';
    switchTab(tab);
});

// 添加游客评论选项联动
document.getElementById('allowGuest').addEventListener('change', function() {
    const guestOptions = document.getElementById('guestOptions');
    const inputs = guestOptions.querySelectorAll('input');
    
    if (this.checked) {
        guestOptions.classList.remove('opacity-50', 'pointer-events-none');
        inputs.forEach(input => input.disabled = false);
    } else {
        guestOptions.classList.add('opacity-50', 'pointer-events-none');
        inputs.forEach(input => input.disabled = true);
    }
});

// 页面加载时初始化游客选项状态
document.addEventListener('DOMContentLoaded', function() {
    const allowGuest = document.getElementById('allowGuest');
    if (!allowGuest.checked) {
        const guestOptions = document.getElementById('guestOptions');
        const inputs = guestOptions.querySelectorAll('input');
        guestOptions.classList.add('opacity-50', 'pointer-events-none');
        inputs.forEach(input => input.disabled = true);
    }
});

// 切换全选
function toggleAllComments() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.getElementsByClassName('comment-checkbox');
    
    Array.from(checkboxes).forEach(checkbox => {
        checkbox.checked = !selectAll.checked;
    });
    
    selectAll.checked = !selectAll.checked;
    updateBatchDeleteButton();
}

// 更新批量删除按钮状态
function updateBatchDeleteButton() {
    const checkboxes = document.getElementsByClassName('comment-checkbox');
    const selectedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    
    batchDeleteBtn.disabled = selectedCount === 0;
    batchDeleteBtn.textContent = `批量删除${selectedCount ? `(${selectedCount})` : ''}`;
}

// 批量删除评论
function batchDeleteComments() {
    const checkboxes = document.getElementsByClassName('comment-checkbox');
    const selectedIds = Array.from(checkboxes)
        .filter(cb => cb.checked)
        .map(cb => cb.value);
    
    if (!selectedIds.length) return;
    
    showAlert(
        `确定要删除选中的 ${selectedIds.length} 条评论吗？此操作不可恢复！`, 
        'warning',
        '确认删除',
        function() {
            fetch('{{ admin_url }}/comments/batch-delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': '{{ csrf_token() }}'
                },
                body: JSON.stringify({
                    comment_ids: selectedIds
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert(data.error, 'error', '错误');
                } else {
                    showAlert('评论已删除', 'success', '成功');
                    setTimeout(() => location.reload(), 500);
                }
            })
            .catch(error => {
                showAlert('删除失败', 'error', '错误');
            });
        },
        true
    );
}

// 监听全选框变化
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.getElementsByClassName('comment-checkbox');
    Array.from(checkboxes).forEach(checkbox => {
        checkbox.checked = this.checked;
    });
    updateBatchDeleteButton();
});
</script>
{% endblock %} 